'use strict';
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableOpacity,
    TextInput,
    TouchableWithoutFeedback,
    Platform,
    ActivityIndicator,
    ScrollView
} from 'react-native';
import Global from '../Commom/GlobalConst';
import PerfectInformationContainer from '../Containers/PerfectInformationContainer';
import * as types from '../Commom/ActionConst';
import LoginContainer from '../Containers/LoginContainer';
import {getCode, userInfo, SMSCodeClearStatus} from '../Action/UserAction';
import UserAPIService from '../Commom/UserAPIService';
import Toast from '../Utils/toast';
import Main from '../Containers/Main';

var totalsmstime = 120;
export default class RegisteredPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputphone: '',
            inputsmscode: '',
            registered_id: '',
            submitting: false,
            sendOK: false,
            showSendButtonText: '获取验证码',
        };
        this.closeKeybord = this.closeKeybord.bind(this);
    }

    closeKeybord() {
        TextInput.State.blurTextInput(TextInput.State.currentlyFocusedField());
    }

    componentWillUnmount() {
        // 如果存在this.timer，则使用clearTimeout清空。
        // 如果你使用多个timer，那么用多个变量，或者用个数组来保存引用，然后逐个clear
        this.timer && clearInterval(this.timer);
    }

    componentDidMount() {
    }

    shouldComponentUpdate(nextProps, nextState) {
        const {dispatch, UserReducer} = nextProps;
        if (UserReducer.kPhoneCode == 200) {
            dispatch(SMSCodeClearStatus());
            this.setState({
                sendOK: true,
                showSendButtonText: '120秒后重发',
            });
            totalsmstime = 120;
            this.timer = setInterval(
                () => {
                    --totalsmstime;
                    this.setState({
                        showSendButtonText: parseInt(totalsmstime) + '秒后重发',
                    });
                    if (totalsmstime === 0) {
                        this.setState({
                            sendOK: false,
                            showSendButtonText: '获取验证码',
                        });
                        clearInterval(this.timer);
                    }
                }, 1000
            );
        }
        return true;
    }

    ClickAction(number) {
        const {dispatch} = this.props;
        switch (number) {
            case 0:
                if (this.state.inputphone.length == 0) {
                    Toast.show('请输入您的手机号');
                    return;
                }
                if (this.state.inputphone.length != 11) {
                    Toast.show('请输入正确的手机号');
                    return;
                }
                if (this.state.sendOK) {
                    return;
                }
                dispatch(getCode(this.state.inputphone))
                break;
            case 1:
                if (this.state.inputphone.length == 0) {
                    Toast.show('手机号不能为空');
                    return;
                }
                if (this.state.inputphone.length != 11) {
                    Toast.show('手机号格式不正确');
                    return;
                }
                if (this.state.inputsmscode.length == 0) {
                    Toast.show('请输入您的验证码');
                    return;
                }
                if (this.state.inputsmscode.length != 6) {
                    Toast.show('验证码格式不正确');
                    return;
                }
                this.timer && clearInterval(this.timer);
                this.setState({
                    sendOK: false,
                    submitting: true,
                    showSendButtonText: '获取验证码',
                });
                dispatch({type: types.kUserLogin});
                UserAPIService.loginFree(this.state.inputphone, this.state.inputsmscode, Global.Const.registeredId).then((ret)=> {
                    if (ret.info_completed == true) {
                        Global.Const.token = ret.token;
                        dispatch({type: types.kUserLoginReceived, result: ret});
                        dispatch(userInfo(ret.token, Global.Const.registeredId));
                        this.setState({
                            submitting: false,
                        });
                        this.props.navigator.popToTop({
                            id: 'Main',
                            component: Main,
                            passProps: {},
                        });
                    } else {
                        dispatch({type: types.kUserLoginReceived, result: ret});
                        Global.Const.token = ret.token;
                        this.setState({
                            submitting: false,
                        });
                        this.props.navigator.push({
                            id: 'PerfectInformationContainer',
                            component: PerfectInformationContainer,
                            passProps: {
                                phone: this.state.inputphone,
                                token: ret.token,
                            },
                        });
                    }
                }).catch((err)=> {
                    this.setState({
                        submitting: false,
                    });
                    dispatch({type: types.kUserLoginReceived, result: null});
                    Toast.show('登录失败');
                });

                break;
            case 2:
                this.props.navigator.push({
                    id: 'LoginContainer',
                    component: LoginContainer,
                    passProps: {},
                });
                break;
        }
    }

    BackAction() {
        this.props.navigator.pop();
    }

    render() {
        return (
            <TouchableWithoutFeedback onPress={()=>this.closeKeybord()}>
                <View style={styles.container}>
                    <View style={{width:Global.Const.size.width,height:65,backgroundColor:'white'}}>

                        <View style={{marginTop:24,alignItems:'center'}}>

                            <View style={{width:21,height:21,position:'absolute',left:12,top:3}}>
                                <TouchableOpacity activeOpacity={0.5}
                                                  onPress={()=>this.BackAction()}>
                                    <Image style={{resizeMode:'contain',width:21,height:21}}
                                           source={require('../../Image/icon_back.png')}></Image>
                                </TouchableOpacity>
                            </View>
                            <Text style={{fontSize:19,color:Global.FontColor.DimGray}}>免密码登录</Text>
                        </View>
                    </View>
                    <ScrollView>
                    <View
                        style={{flex:1,alignItems:'center',backgroundColor:'white', borderTopWidth:3,borderColor:Global.Const.transparent}}>
                        <Image style={{width:100,height:100,borderRadius:50,marginTop:50}}
                               source={require('../../Image/icon_logo.png')}></Image>

                        <View
                            style={{alignItems:'center',marginTop:30,width:Global.Const.size.width,height:45,backgroundColor:'white',flexDirection:'row'}}>
                            <Image style={{resizeMode:'contain',width:18,height:18,marginLeft:40}}
                                   source={require('../../Image/call_icon.png')}></Image>
                            <TextInput
                                style={{marginLeft:5,width:Global.Const.size.width-195,fontSize:13}}
                                value={this.state.inputphone}
                                onChangeText={inputphone => this.setState({ inputphone })}
                                placeholder={'请输入您的手机号'}
                                maxLength={11}
                                keyboardType={'numeric'}
                                underlineColorAndroid={'transparent'}></TextInput>
                            <View style={{width:1,height:30,backgroundColor:Global.Const.transparent}}></View>
                            <TouchableOpacity activeOpacity={0.5}
                                              onPress={()=>this.ClickAction(0)}>
                                <Text style={{color:'#24CD78',marginLeft:8}}>{this.state.showSendButtonText}</Text>
                            </TouchableOpacity>
                        </View>
                        <View
                            style={{width:Global.Const.size.width-80,height:1,backgroundColor:Global.Const.transparent,marginLeft:40,marginRight:40}}></View>
                        <View
                            style={{alignItems:'center',width:Global.Const.size.width,height:45,marginTop:20,backgroundColor:'white',flexDirection:'row'}}>
                            <Image style={{resizeMode:'contain',width:18,height:18,marginLeft:40}}
                                   source={require('../../Image/icon_identifying_code.png')}></Image>
                            <TextInput
                                style={{marginLeft:5,flex:1,fontSize:13}}
                                value={this.state.inputsmscode}
                                onChangeText={inputsmscode => this.setState({ inputsmscode })}
                                placeholder={'请输入您的验证码'}
                                maxLength={20}
                                keyboardType={'numeric'}
                                underlineColorAndroid={'transparent'}></TextInput>

                        </View>
                        <View
                            style={{width:Global.Const.size.width-80,height:1,backgroundColor:Global.Const.transparent,marginLeft:40,marginRight:40}}></View>

                        <TouchableOpacity activeOpacity={0.5}
                                          onPress={()=>this.ClickAction(1)}>
                            <View
                                style={{marginTop:35,backgroundColor:'#24CD78',borderRadius:20, marginLeft:30,marginRight:30,marginBottom:10,width:Global.Const.size.width-60,height:40, alignItems:'center',justifyContent:'center'}}>
                                <Text style={{color:'white',fontSize:16}}>登录</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.5}
                                          onPress={()=>this.ClickAction(2)}>
                            <View
                                style={{marginTop:80,backgroundColor:'white',marginLeft:30,marginRight:30,marginBottom:10,width:Global.Const.size.width-60,height:40, alignItems:'center',justifyContent:'center'}}>
                                <Text style={{color:Global.FontColor.LightGrey,fontSize:13}}>账号密码登录</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    {this.state.submitting ? <View
                        style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                        <View
                            style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                            <ActivityIndicator
                                animating={this.state.animating}
                                style={{ alignItems: 'center',justifyContent: 'center'}}
                                size="large"/>
                            <Text style={{color:'white'}}>正在登录</Text>
                        </View>
                    </View> : null}
                    </ScrollView>

                </View>
            </TouchableWithoutFeedback>
        );
    }
}

var styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
    },
});
